//
//  ContactListViewController.m
//  SSNDB
//
//  Created by nako on 9/16/11.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "ContactListViewController.h"
#import "SSNDBAppDelegate.h"
#import "Contact.h"

@implementation ContactListViewController

/* ------------------------------------------- */
@synthesize tableViewContactList;
@synthesize arrayOfContactList;
@synthesize addButton;
@synthesize receiveData;


/* ------------------------------------------- */

#pragma mark -
#pragma mark === Table View Delegate ===
#pragma mark -

/* ------------------------------------------- */

- (void) setReceiveData:(NSString *)paramValue{
	if (paramValue != receiveData) {
		[receiveData release];
		receiveData = [paramValue copy];
	}
}

- (void)              tableView:(UITableView*)tableView 
 willBeginEditingRowAtIndexPath:(NSIndexPath *)indexPath{
	
	if ([tableView isEqual:self.tableViewContactList] == YES){
		if (self.tableViewContactList.editing == NO){
			[self setEditingModeNavigationBarButtons];
		}
	}
	
}

/* ------------------------------------------- */

- (void)              tableView:(UITableView*)tableView 
    didEndEditingRowAtIndexPath:(NSIndexPath *)indexPath{
	
	if ([tableView isEqual:self.tableViewContactList] == YES){
		if (self.tableViewContactList.editing == NO){
			[self setDefaultNavigationBarButtons];
		}
	}
	
}

/* ------------------------------------------- */

- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView
		   editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath{
	
	UITableViewCellEditingStyle result =
	UITableViewCellEditingStyleNone;
	
	if ([tableView isEqual:self.tableViewContactList] == YES){
		/* Allow the user to delete items from the table while we are
		 in the editing mode */
		result = UITableViewCellEditingStyleDelete;
	}
	
	return(result);
	
}


/* ------------------------------------------- */

#pragma mark -
#pragma mark === Table View Data Source ===
#pragma mark -

/* ------------------------------------------- */

- (void)  tableView:(UITableView *)tableView 
 commitEditingStyle:(UITableViewCellEditingStyle)editingStyle
  forRowAtIndexPath:(NSIndexPath *)indexPath{
	
	if ([tableView isEqual:self.tableViewContactList] == YES){
		
		/* Only allow deletion in the editing mode */
		if (editingStyle != UITableViewCellEditingStyleDelete){
			return;
		}
		
		/* Make sure our array contains the item that is about to
		 be deleted from the table view */
		if ([self.arrayOfContactList count] <= indexPath.row){
			return;
		}
		
		/* Get the person that has to be deleted from the array */
		Contact *thisContactList = 
		[self.arrayOfContactList objectAtIndex:indexPath.row];
		
		// AppDelegate_Shared *delegate = (AppDelegate_Shared *)
		// [[UIApplication sharedApplication] delegate];
		
		/* Attempt to delete the person from the context */
		//[delegate.managedObjectContext deleteObject:thisPerson];
		// delete sqlite db...[Nako]
		
		/* And we also have to save the context after deletion */
		
		//NSError *savingError = nil;
		//if ([delegate.managedObjectContext save:&savingError] == YES){
		
		/* Remove the person from the array and also make sure that
		 we remove the corresponding cell from the table 
		 preferrably with an animation */
		
		[self.arrayOfContactList removeObject:thisContactList];
		
		NSArray *cellsToDelete = [NSArray arrayWithObject:indexPath];
		
		[tableView 
		 deleteRowsAtIndexPaths:cellsToDelete
		 withRowAnimation:UITableViewRowAnimationFade];
		
		//} else {
		/* An error happened here */
		//}
		//*/
	}
	
}

/* ------------------------------------------- */

- (NSInteger)tableView:(UITableView *)table 
 numberOfRowsInSection:(NSInteger)section{
	
	NSInteger result = 0;
	
	if ([table isEqual:self.tableViewContactList] == YES){
		
		if (self.arrayOfContactList != nil){
			result = [self.arrayOfContactList count];
		}
		
	}
	
	
	return(result);
	
}

/* ------------------------------------------- */

- (void) viewDidAppear:(BOOL)animated{
	[super viewDidAppear:animated];
	
	/* Make sure we read the array of all the people in the
	 managed object context and reload our table with
	 the latest data. If in the Add New Person 
	 View Controller, we actually do add a person and
	 come back to this screen, our table view will refresh 
	 itself automatically this way */
	
	[self readAllContactList];
}

/* ------------------------------------------- */

- (UITableViewCell *)tableView:(UITableView *)tableView 
         cellForRowAtIndexPath:(NSIndexPath *)indexPath{
	
	UITableViewCell *result = nil;
	
	if ([tableView isEqual:self.tableViewContactList] == YES){
		
		static NSString *SimpleIdentifier = @"ContactListCell";
		
		result = 
		[tableView 
		 dequeueReusableCellWithIdentifier:SimpleIdentifier];
		
		/* A cell with sub title */
		if (result == nil){
			result = [[[UITableViewCell alloc] 
					   initWithStyle:UITableViewCellStyleSubtitle
					   reuseIdentifier:SimpleIdentifier] autorelease];
		}
		
		if (self.arrayOfContactList != nil){
			
			Contact *thisContactList = 
			[self.arrayOfContactList objectAtIndex:indexPath.row];
			
			/* The title will be "Last Name, First Name" */
			//NSLog(@"%@",receiveData);
			if ([thisContactList.SSN isEqualToString:receiveData] == TRUE) {
				NSLog(@"Match %@",thisContactList.Contact_date);
				result.textLabel.text = 
				[NSString stringWithFormat:@"%@",
				 thisContactList.Contact_date];
			}
			/* The sub title will be the age */
			
			//result.detailTextLabel.text = 
			//[NSString stringWithFormat:@"Age %ld",
			// (long)[thisPerson.age integerValue]];
			
			result.selectionStyle =
			UITableViewCellSelectionStyleNone;
			
		}
		
	}
	
	return(result);
	
}

/* ------------------------------------------- */

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
	
	NSInteger result = 0;
	
	if ([tableView isEqual:self.tableViewContactList] == YES){
		/* We only have one section */
		result = 1;
	}
	result =1;
	
	return(result);
	
}
/* ------------------------------------------- */

#pragma mark -
#pragma mark === Select Item ===
#pragma mark -

/* ------------------------------------------- */
- (void)tableView:(UITableView *)tableView 
didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    /*
	 if ([tableView isEqual:self.tableViewContactList] == YES){
	 if (self.arrayOfContactList != nil){
	 Person *thisPerson = 
	 [self.arrayOfContactList objectAtIndex:indexPath.row];
	 if (self.contectListViewController == nil) {
	 ContactListViewController *viewController = [[ContactListViewController alloc] initWithNibName:@"ContactListViewController" bundle:nil];
	 self.contectListViewController = viewController;
	 [viewController release];
	 }
	 [self.navigationController pushViewController:self.contectListViewController animated:YES];
	 //NSLog(@"Select Item :%@",thisPerson.Name);
	 self.contectListViewController.title = [thisPerson Name];
	 }
	 }
	 */
}

/* ------------------------------------------- */

#pragma mark -
#pragma mark === Instance Methods ===
#pragma mark -

/* ------------------------------------------- */

- (id)initWithNibName:(NSString *)nibNameOrNil 
               bundle:(NSBundle *)nibBundleOrNil {
	
	if ((self = [super initWithNibName:nibNameOrNil
								bundle:nibBundleOrNil])) {
		
		self.title = NSLocalizedString(@"ContactList", nil);
		/* Make sure we instantiate this array */
		NSMutableArray *newArray = [[NSMutableArray alloc] init];
		arrayOfContactList = [newArray retain];
		[newArray release];
		
	}
	
	return(self);
}

/* ------------------------------------------- */

- (BOOL) readAllContactList{
	
	BOOL result = NO;
	
	if (self.arrayOfContactList == nil){
		return(NO);
	}
	
	SSNDBAppDelegate *appDelegate = (SSNDBAppDelegate *)[[UIApplication sharedApplication] delegate];
	
	
	NSMutableArray *contactList = [NSMutableArray array];
	contactList = [appDelegate.contacts mutableCopy]; 
	
	/* Make sure we could read the data */
	if (contactList != nil){
		
		/* Add all the persons from the array to our array */
		[self.arrayOfContactList removeAllObjects];
		[self.arrayOfContactList addObjectsFromArray:contactList];
		[self.tableViewContactList reloadData];
		result = YES;
		
	}
	
	return(result);
	
}

/* ------------------------------------------- */

- (void) performaddNewContactList:(id)paramSender{
	
	/* Just display the Add New Person View Controller */
	/*
	 AddNewPersonViewController_iPhone *controller = 
	 [[AddNewPersonViewController_iPhone alloc] 
	 initWithNibName:@"AddNewPersonViewController_iPhone"
	 bundle:nil];
	 
	 [self.navigationController pushViewController:controller
	 animated:YES];
	 
	 [controller release];
	 */
	NSLog(@"@@@@@@@@@@@@@@@@@ New ContactList");
}

/* ------------------------------------------- */

- (void) performDoneEditing:(id)paramSender{
	
	/* Take the table view out of the editing mode and re-create
	 the default navigation bar buttons */
	
	[self.tableViewContactList setEditing:NO
								 animated:YES];
	
	[self setDefaultNavigationBarButtons];
	
}

/* ------------------------------------------- */

- (void) performEditTable:(id)paramSender{
	
	/* Take the table to the editing mode */
	[self setEditingModeNavigationBarButtons];
	
	[self.tableViewContactList setEditing:YES
								 animated:YES];
	
}
/* ------------------------------------------- */

- (void) setEditingModeNavigationBarButtons{
	
	/* In the editing mode, we just want a Done button on the
	 top left hand corder of the navigation bar to take the
	 table view out of the editing mode */
	
	[self.navigationItem setRightBarButtonItem:nil
									  animated:YES];
	
}

/* ------------------------------------------- */

- (void) setDefaultNavigationBarButtons{
	
	/* Here we set an add button (+) on the top right and
	 an edit button on the top left that will take our table
	 view into editing mode where the user can delete items from
	 the table and our managed object context */
	
	[self.navigationItem setRightBarButtonItem:self.addButton
									  animated:YES];
	
}

/* ------------------------------------------- */

- (void)viewDidLoad {
	[super viewDidLoad];
    
	UIBarButtonItem *newAddButton = 
	[[UIBarButtonItem alloc]
	 initWithBarButtonSystemItem:UIBarButtonSystemItemAdd
	 target:self
	 action:@selector(performaddNewContactList:)];
	self.addButton = newAddButton;
	[newAddButton release];
	
	[self setDefaultNavigationBarButtons];
	
	self.tableViewContactList.rowHeight = 60.0f;
	
}

/* ------------------------------------------- */

- (void)viewDidUnload {
	[super viewDidUnload];
	
	/* Free up some memory space */
	
	self.tableViewContactList = nil;
	self.arrayOfContactList = nil;
	self.addButton = nil;
	
	self.navigationItem.rightBarButtonItem = nil;
	self.navigationItem.leftBarButtonItem = nil;
	
}

/* ------------------------------------------- */

- (BOOL)shouldAutorotateToInterfaceOrientation:
(UIInterfaceOrientation)interfaceOrientation {
	// Return YES for supported orientations
	return (YES);
}

/* ------------------------------------------- */

- (void)didReceiveMemoryWarning {
	[super didReceiveMemoryWarning];
}

/* ------------------------------------------- */

- (void)dealloc {
	
	[receiveData release];
	[arrayOfContactList release];
	[tableViewContactList release];
	[addButton release];
	
	[super dealloc];
}

/* ------------------------------------------- */

@end
